# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.views.generic import TemplateView, ListView, DetailView, CreateView
from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render_to_response

from .models import Login,Customer
from .utility import WXUserInfo
import datetime
import time
		 
def login(request):
	url = WXUserInfo.getOauth2Url("http://weixin.fanligame.com/home")
	return HttpResponseRedirect(url) 

#用于验证token
def index(request):
    echostr = request.GET.get('echostr', '')
    return HttpResponse(echostr)
#用于验证微信业务域
def vertifyfile(request):
    return HttpResponse("BXRVCCIcJ6I9IkJo")

# Create your views here.
class HomeView(TemplateView):
	template_name = 'index.html'
	def get_context_data(self, **kwargs):
		context = super(HomeView, self).get_context_data(**kwargs)
		code = self.request.GET.get('code', '')
		WX = WXUserInfo(code)
		#获取用户信息
		data = WX.getUser()
		#data = json.loads(res)
		headimgurl = data["headimgurl"]
		openid = data["openid"]
		nickname =  data["nickname"]
		sex = data["sex"]
		province = data["province"]
		city = data["city"]
		country = data["country"]
		privilege = data["privilege"]
		privilege = ""
		#unionid = data["unionid"]
		
		logintime = str(datetime.datetime.now());
		loginobj = Login(openid = openid,nickname = nickname,logintime = logintime)
		loginobj.save()
	
		obj = Customer.objects.filter(openid=openid)
		if not obj:#为空情况
			customer = Customer(
			openid = openid,nickname = nickname,sex = sex ,
			province = province, city= city,country = country,
			privilege = privilege,headimgurl= headimgurl
			)
			customer.save()
		else:
			customer = obj[0]
			customer.nickname = nickname
			customer.sex = sex
			customer.province = province
			customer.city = city
			customer.country = country
			customer.privilege = privilege
			customer.headimgurl = headimgurl
			customer.save()	

		return context




